<template>
    <div class="chart-view" :class="{'live-update':autoRefresh}">
        <div class="chart-view-card" v-if="config.type == 3">
            <div class="num">
                <span class="txt">{{chartData[0] ? chartData[0][0] : 0}}</span>
            </div>
            <div class="name">
                <span class="txt">{{name}}</span>
            </div>
        </div>
        <ChartViewLine :name="name" @fullscreen="fullscreenChart" :source="chartData" :contrastsNum="contrastsNum" :colors="colors" v-if="config.type == 0" :autoRefresh="autoRefresh"></ChartViewLine>
        <ChartViewBar :name="name" @fullscreen="fullscreenChart" :source="chartData" :contrastsNum="contrastsNum" :colors="colors" v-if="config.type == 1" :autoRefresh="autoRefresh"></ChartViewBar>
        <ChartViewPie :name="name" @fullscreen="fullscreenChart" :source="chartData" :colors="colors" v-if="config.type == 2" :autoRefresh="autoRefresh"></ChartViewPie>
      <div v-if="config.type == 4">
        <x-table :cell-bordered="false" style="width: 100%" class="table_chart">
          <thead>
              <tr>
                <th v-for="(item,index) in chartData[0]" :key="index">{{item}}</th>
              </tr>
          </thead>
          <tbody>
            <tr v-for="(item,index) in chartData.slice(1)" :key="index">
              <td v-for="(ele,i) in item" :key="i">{{ele}}</td>
            </tr>
          </tbody>
        </x-table>
      </div>
      <template>
        <div class="chart-fullscreen" v-if="config.type !== 3" v-show="showFullscreen">
          <div class="chart-title">
              <span>
                  {{groupItem.name}}
              </span>
              <div class="group-list" v-if="groupItem.widgetLayouts.length > 1">
                  <span class="list-item" :class="{active:groupItem.widgetIndex===widgetIndex}" @click="changeWidgetIndex(groupItem,widgetIndex)" v-for="(widgetItem,widgetIndex) in groupItem.widgets" :key="widgetIndex">{{ groupItem.widgetLayouts && groupItem.widgetLayouts[widgetIndex].nameAlias }}</span>
              </div>
          </div>
          <div v-show="config.type !== 4" class="e-chart" ref="fullscreenChart"></div>
          <div  v-if="config.type === 4">
            <x-table :cell-bordered="false" style="width: 100%" class="table_chart">
              <thead>
                  <tr>
                    <th v-for="(item,index) in chartData[0]" :key="index">{{item}}</th>
                  </tr>
              </thead>
              <tbody>
                <tr v-for="(item,index) in chartData.slice(1)" :key="index">
                  <td v-for="(ele,i) in item" :key="i">{{ele}}</td>
                </tr>
              </tbody>
            </x-table>
          </div>
        </div>
      </template>
    </div>
</template>

<script>
    import DataAnalysisDao from "@/daos/data_analysis_dao"
    import ChartViewLine from "./chart_view_line"
    import ChartViewBar from "./chart_view_bar"
    import ChartViewPie from "./chart_view_pie"
    import { XTable } from 'vux'
    // const echarts = require('echarts/lib/echarts');
    import axios from 'axios';
    export default {
        name: "chart-view",
        components: {
            ChartViewLine,
            ChartViewBar,
            ChartViewPie,
            XTable
        },
        props: {
            config: {
                type: Object,
            },
            name: {
                type: String,
                default: '未命名图表'
            },
            groupItem: {
                type: Object,
                default: ()=>{
                  return {}
                }
            },
        },
        data() {
            return {
                timeInterval: null,
                fullchart: null,
                showFullscreen: false,
                autoRefresh: false,
                autoRefreshTime: 10,
                colors: ["#41CCD8", "#456DE6", "#54CB75", "#FAD74A", "#FA4B48", "#8C55DC", "#CD780A", "#DC6EE4", "#5050C8", "#C82864"],
                chartData: [],
                contrastsNum:''
            }
        },
        methods: {            
            // 时间格式化
            dateFormat(fmt, dateStr) {
                let date = new Date(dateStr);
                if(date == "Invalid Date"){                    
                    return dateStr;
                }else{
                    let o = { 
                        "M+" : date.getMonth()+1,
                        "d+" : date.getDate(),
                        "h+" : date.getHours(),
                        "m+" : date.getMinutes(),
                        "s+" : date.getSeconds(),
                        "q+" : Math.floor((date.getMonth()+3)/3),
                        "S" : date.getMilliseconds()
                    }; 
                    if(/(y+)/.test(fmt)){
                        fmt = fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
                    };
                    for(var k in o) {
                        if(new RegExp("("+ k +")").test(fmt)) {
                            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); 
                        }
                    };
                    return fmt; 
                }; 
            },
            // 渲染图表
            render() {
              if (+this.config.autoRefresh) {
                this.autoRefresh = true
                this.autoRefreshTime = this.config.autoRefreshTime || 10
                this.setLiveUpdata()
              }
              this.getData()
            },
            getData(){
                if ((this.config.type == 3 && this.config.indicatrixs.length > 0) || (this.config.type == 4 && this.config.indicatrixs.length > 0) || (this.config.type < 3 && this.config.indicatrixs.length > 0 && this.config.dimensions.length > 0)) {
                    // 请求图表数据
                  this.contrastsNum = this.config.contrasts.length
                    DataAnalysisDao.widgetAnalysis(this.config, (data) => {
                        if (data && data.length > 0) {
                            // 维度格式化
                            let source = [data[0]];
                            if(this.config.format){
                                let list = [];
                              data.forEach((item, index) => {
                                if(index > 0){
                                  let str = this.dateFormat(this.config.format, item[0]);
                                  let index = list.indexOf(str);
                                  if(index > -1){
                                    item.forEach((x,i)=>{
                                      if(i>0){
                                        source[index + 1][i] += x*1;
                                      }
                                    })
                                  }else{
                                    let listChild = [str]
                                    item.forEach((x,i)=>{
                                      if(i>0){
                                        listChild.push(x*1)
                                      }
                                    })
                                    source.push(listChild);
                                    list.push(str);
                                  };
                                }
                              });
                              this.$set(this,'chartData', source)
                              // this.chartData = source;
                            }else{
                              this.$set(this,'chartData', data)
                              // this.chartData = data;
                            };
                        }
                    this.$vux.loading.hide()
                    });
                } else {
                    this.$vux.loading.hide()
                    this.chartData = [];
                }
            },
            setLiveUpdata(){
              clearInterval(this.timeInterval)
              this.timeInterval = setInterval(()=>{ 
                // this.postLiveUpdateData()
                this.getData()
                if (this.showFullscreen) {
                  this.fullscreenChartUpdate()
                }
               }, this.autoRefreshTime * 1000);
            },
            changeWidgetIndex(item, index){
              this.$emit('changeWidgetIndex',item, index)
              // this.fullscreenChartUpdate()
            },
            postLiveUpdateData(){
              let data = {
                appId: "iuvQkBf",
                token: "6012ffbff6a7b06469a95d1dc887b031",
                departmentId: "",
                data: [
                  {
                    dataCode: "FE00FE00-X08",
                    value: Math.round(Math.random()*100),
                    deviceId: "",
                    groupCode: "",
                    description: "",
                  },
                ],
              };
              axios.post("http://117.78.43.248:10031/api/uploadToIUCloud", data).then((e) => {
                console.log(e);
              }).catch(err=>{
                console.log(err);
              });
            },
            fullscreenChart(option, tag){
              if (!tag) {
                if (this.showFullscreen) {
                  this.showFullscreen = false
                } else {
                  this.showFullscreen = true
                }
              }
              this.$nextTick(e=>{
                if (!this.fullchart) {
                  this.fullchart = this.$echarts.init(this.$refs.fullscreenChart)
                }
                if (tag) {
                  let _scope = this;
                  // option.legend = option.legend
                  option.toolbox = {
                    show: true,
                    iconStyle:{
                    color:'#fff',
                    borderColor:'#fff',
                    },
                    feature: {
                      myFull: {
                          show: true,
                          title: '全屏查看',
                          icon: 'path://M85.333333 682.666667v128a128 128 0 0 0 128 128h128a42.666667 42.666667 0 0 0 0-85.333334H213.333333a42.666667 42.666667 0 0 1-42.666666-42.666666v-128a42.666667 42.666667 0 0 0-85.333334 0z m597.333334 256h128a128 128 0 0 0 128-128v-128a42.666667 42.666667 0 0 0-85.333334 0v128a42.666667 42.666667 0 0 1-42.666666 42.666666h-128a42.666667 42.666667 0 0 0 0 85.333334z m256-597.333334V213.333333a128 128 0 0 0-128-128h-128a42.666667 42.666667 0 0 0 0 85.333334h128a42.666667 42.666667 0 0 1 42.666666 42.666666v128a42.666667 42.666667 0 0 0 85.333334 0zM341.333333 85.333333H213.333333a128 128 0 0 0-128 128v128a42.666667 42.666667 0 0 0 85.333334 0V213.333333a42.666667 42.666667 0 0 1 42.666666-42.666666h128a42.666667 42.666667 0 0 0 0-85.333334z',
                          onclick (e){
                              _scope.fullscreenChart()
                          }
                      }
                    }
                  }
                  console.log(option);
                  this.fullchart.setOption(option, true)
                  this.fullscreenChartUpdate()
                }
              })
            },
            fullscreenChartUpdate(){
                this.fullchart.setOption({
                    dataset: {
                      source: this.chartData
                    }
                });
            },
        },
        // created() {
          // _scope = this
        // },
        beforeDestroy() {
          // _scope = null
          clearInterval(this.timeInterval)
        },
        watch: {
            config: {
                handler(newValue, oldValue) {
                  // console.log('reder',newValue,oldValue);
                    this.render();
                },
                deep: true,
                immediate: true,
            },
        },
    }
</script>

<style lang="less" scoped>
    .chart-view {
        // height: 100%;
        height: 250px;
        // padding: 0 5px;
        box-sizing: border-box;
        &.live-update{
          height: 250px;
        }
        .chart-view-card {
            // height: 100%;
            color: #fff;
            text-align: center;

            .num, .name {
                width: 100%;
                height: 30%;
                font-size: 12px;
                display: flex;
                justify-content: center;
                align-items: center;

                .txt {
                    width: 100%;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                }
            }

            .num {
                // height: 60%;
                font-size: 20px;
            }
        }

        .e-chart {
            width: 100%;
            height: 100%;
            padding: 5px 0;
        }
    }
.chart-fullscreen{
    width: 100vh;
    height: 100vw;
    position: fixed;
    top: -100vw;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 19999999;
    transform: rotate(90deg);
    transform-origin: bottom left;
    background-color: #23233d;
    .e-chart {
      height: calc(~"100vw" - 31px);
      width: 100vh;
    }
    .chart-title{
        padding: 6px 8px;
        font-size: 14px;
        text-align: left;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .group-list {
        font-size: 12px;
        display: flex;
        justify-content: center;
        border: 1px solid #456de6;
        border-radius: 2px;
        .list-item {
            padding: 0 12px;
            text-align: center;
            color: #456de6;
            flex: 1;
            white-space: nowrap;
            &.active {
                color: #fff;
                background-color: #456de6;
            }
        }
    }
}
</style>
<style lang="less">
  .chart-view {
    .table_chart{
      max-height: 200px;
    }
    .el-table__body-wrapper{
      max-height: 4rem;
      overflow-y: auto;
    }
    .el-table, .el-table__expanded-cell {
      background-color: #23233D;
    }
    .el-table th, .el-table tr {
      background-color: #23233D;
    }
    .el-table thead {
      color: #fff;
      font-weight: 500;
    }
    .el-table{
      color: rgba(255,255,255,0.6);
    }
    .el-table__body tr.hover-row>td{
      background-color: #23233D;
    }
    .el-table--enable-row-hover .el-table__body tr:hover>td {
      background-color: #23233D;
    }
    .el-table::before {
      left: 0;
      bottom: 0;
      width: 100%;
      height: 0px;
    }
    .el-table .cell {
      white-space: nowrap;
    }
    .el-table__header {
      line-height: 0.7rem !important;
    }
    .el-table td, .el-table th {
      padding: 0.25rem 0;
    }
  }
</style>
